/*
 * Time    : 2021-09-07 08:59:12
 * Author  : Gray Snail
 * Version : 1.0
 * Contact : shtao2011@sina.com
 * License : Copyright (c) 2021 Gray Snail
 * Desc    : 画带点矩形框
 *
 * 注:
 *   mouse drag 会屏蔽 mouse move 事件
 *   tool 鼠标事件屏蔽 path 鼠标事件
 *
 * 操作说明:
 *
 * 左击: 画框,右键可取消
 * 右击: 选中,选中的框会显示锚点
 *     在选中的框上按住左键拖动,修改框的位置
 *     鼠标移动到选中标注的锚点,修改框的位置和大小
 * 按下delete键,删除选中的框

 */

import paper from 'paper'
import { Cursor, KeyCode, Style } from './const'
import { AnnoType } from '../data/annotation'

import HandlePoint from './HandlePoint'
import RectTool, { AnnoRect } from './rect'

class AnnoRectPt extends AnnoRect {
  constructor(from, to) {
    super(from, to)

    const bound = this.rect.bounds
    const point = new HandlePoint({ segments: [bound.bottomCenter], cursor: Cursor.Crosshair })
    point.visible = true
    this.addChild(point)
    this.rectPoint = point
    // hit-test: fill
    this.fillColor = new paper.Color(1, 1, 1, 0.1)
    this.opacity = 1
    this.fullySelected = true
  }

  get annoType() {
    return AnnoType.RECT_PT
  }

  movePoint(point, newPoint) {
    const rectPtPos = this.rectPoint.position
    if (rectPtPos.x === point.x && rectPtPos.y === point.y) {
      if (this.rect.contains(newPoint)) {
        this.rectPoint.position = newPoint
        point.x = newPoint.x
        point.y = newPoint.y
      }
      this.triggerEvnet()
    } else {
      this.rectPoint.position = this.rect.bounds.bottomCenter
      super.movePoint(point, newPoint)
    }
  }

  get pts() {
    const pts = super.pts
    const { x, y } = this.rectPoint.position
    pts.push({ x, y })
    return pts
  }
}

export default class RectPointTool extends RectTool {
  static get meta() {
    return {
      icon: 'el-icon-news',
      desc: '矩形框带点',
    }
  }

  get meta() {
    return { ...RectPointTool.meta, name: this.name }
  }

  // 创建 Annotation
  createItem(from, to) {
    return new AnnoRectPt(from, to)
  }
}
